var express = require('express');
const {getCurrentTime, execCommand, readResultLines, loadDir} = require("../utils/utils");
const {successData} = require("../utils/response");
var router = express.Router();

/* GET home page. */
router.get('/', function (req, res, next) {
    res.render('index', {title: 'Express'});
});

//执行cmd命令请求
router.get('/runCmd', async function (req, res, next) {
    res.writeHead(200, {
        'Content-Type': 'text/event-stream;charset=utf-8',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
    })
    res.write(`data:${getCurrentTime()} #### runCmd start\n\n`);
    let {commandList} = req.query;
    commandList = JSON.parse(decodeURIComponent(commandList));

    //循环执行多条命令
    for (let i = 0; i < commandList.length; i++) {
        let commandItem = commandList[i];
        console.log("commandItem", commandItem);
        try {
            res.write(`data:${getCurrentTime()} #### ${commandItem}\n\n`);
            let result = await execCommand(commandItem);
            let {stdout, error, stderr} = result;
            console.log("result====", i, result);
            readResultLines(stdout || stderr || "执行完成！").forEach(item => res.write(`data:${getCurrentTime(true)}==== ${item}\n\n`));
        } catch (e) {
            readResultLines(e.message).forEach(item => res.write(`data:${getCurrentTime(true)}==== ${item}\n\n`));
            break
        }
    }
    //结束标志
    res.write(`data:${getCurrentTime()} #### runCmd end\n\n`);
    res.write(`data:end\n\n`);
    res.end();
})

//获取项目路径
router.get("/getProjectDir", async function (req, res, next) {
    let WorkPlace = loadDir("/Users/zhaoyj/WorkPlace", 2, ["mac"])
    let zyj_pc = loadDir("/Users/zhaoyj/zyj_pc", 3, ["CloudMusic"])
    res.json(successData({WorkPlace, zyj_pc}))
})

module.exports = router;
